package org.bbs.demo.user.api;

import org.bbs.demo.advice.SysException;
import org.bbs.demo.common.BBSConstants;
import org.bbs.demo.common.Result;
import org.bbs.demo.user.dao.GetAvatarDao;
import org.bbs.demo.user.dto.AvatarDto;
import org.bbs.demo.utils.jwtutil.JWTutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/user/avatar")
@Transactional
public class GetAvatarApi {

    @Autowired
    GetAvatarDao getAvatarDao;

    @PostMapping("/get")
    public Result getAvatar(@RequestHeader(BBSConstants.HEADER_PARAM_TOKEN) String token, HttpServletResponse response) throws IOException {

        // 获取头像信息
        AvatarDto avatarDto = this.getAvatarInfo(token);

        // response 表示响应对象，负责向浏览器输出
        OutputStream out = response.getOutputStream();  //向浏览器输出的输出流
        // 读取文件的输入流
        InputStream in = new FileInputStream(BBSConstants.UPLOAD_DIR + "/" + avatarDto.getAvatar());

        byte[] buffer = new byte[1024*1024];
        int len = -1;   //每次从流中读取的字节数

        while((len = in.read(buffer))!= -1 ){
            out.write(buffer,0,len);
        }

        out.flush();
        out.close();
        in.close();
        return Result.OK();

    }

    // 从数据库获取头像信息
    private AvatarDto getAvatarInfo(String token){

        // 从token获取用户id  设置默认头像路径
        AvatarDto avatarDto = new AvatarDto(JWTutil.getUserID(token), BBSConstants.DEFAULT_AVATAR_NAME);

        // 获取用户头像路径
        String filename = null;
        try {
            filename = getAvatarDao.getAvatarByUid(avatarDto);
        }catch (Exception e){
            throw new SysException("数据库查询错误");
        }

        if (filename != null && !filename.equals("")){
            avatarDto.setAvatar(filename);
        }

        return avatarDto;
    }
}
